package com.zlzxm.sorting.usermanager;

import android.text.TextUtils;

import com.tencent.mmkv.MMKV;
import com.zlzxm.sorting.globe.Constant;

/**
 * CREATE BY zlzxm ON 2022/8/3
 */
public class UserManager {

    private UserManager() {
    }

    private static class UserManagerHold{

        private static UserManager userManager = new UserManager();

    }

    public static UserManager getInstance(){

        return UserManagerHold.userManager;
    }

    private String token;

    private User user;

    public boolean loadLocalToken(){

        token = MMKV.defaultMMKV().getString(Constant.MMKV_KEY.TOKEN,token);
        user = MMKV.defaultMMKV().decodeParcelable(Constant.MMKV_KEY.USER,User.class);
        return isLogin();
    }

    public void login(String token){
        MMKV.defaultMMKV().encode(Constant.MMKV_KEY.TOKEN,token);
        this.token = token;

    }

    public void login(String token,User user){
        MMKV.defaultMMKV().encode(Constant.MMKV_KEY.TOKEN,token);
        MMKV.defaultMMKV().encode(Constant.MMKV_KEY.USER,user);
        this.token = token;
        this.user = user;

    }

    public void logOut(){
        MMKV.defaultMMKV().removeValueForKey(Constant.MMKV_KEY.TOKEN);
        MMKV.defaultMMKV().removeValueForKey(Constant.MMKV_KEY.USER);
        token = null;
        user = null;

    }

    public boolean isLogin(){


        return !TextUtils.isEmpty(token);
    }

    public String getToken(){

        return token;
    }

    public User getUser(){

        if(!isLogin()){

            return null;
        }

        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
